<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
</head>

<body>
  <ul>
    <li><a href="/home">首页</a></li>
    <li><a href="/about">关于</a></li>
  </ul>



  <!-- 渲染对应的代码块 -->
  <div id="view"></div>
  <script>

    let view = $('#view')
    let dom = `<div class="home">
    <a href="/about">go about</a>
    <p>这是首页</p>
  </div>`

    let dom2 = `<div class="about">
    <a href="/detail">go detail</a>
    <p>这是about page</p>
  </div>`
    let dom3 = `<h1>详情页</h1>`


    let links = document.querySelectorAll('a[href]')
    window.addEventListener('DOMContentLoaded', load)
    window.addEventListener('popstate',()=>{
      if (location.pathname === '/home') {
            view.html(dom)
          } else if (location.pathname === '/about') {
            view.html(dom2)
          }
    })

    function load() {
      links.forEach(link => {

        link.addEventListener('click', (e) => {
          e.preventDefault()  //阻止a标签的默认跳转
          // 跳转页面的
          let url = e.target.getAttribute('href')
          history.pushState(null, '', url)
          // history.pushState(null,'',link.getAttribute('href'))
          if (url === '/home') {
            view.html(dom)
          } else if (url === '/about') {
            view.html(dom2)
          }
        })
      })

      if (location.pathname === '/home') {
        view.html(dom)
      } else if (location.pathname === '/about') {
        view.html(dom2)
      }

    }
    console.log(links);
  </script>
</body>

</html>